﻿using DataManageSystem.Common;
using DataManageSystem.Data;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Models.Dto;
using DataManageSystem.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MonitorController : ControllerBase
    {
        private readonly MonitorDevServices monitorDevService;
        private readonly ApplicationDbContext _context;

        public MonitorController(
            MonitorDevServices monitorDevServices,
            ApplicationDbContext applicationDbContext
        )
        {
            monitorDevService = monitorDevServices;
            _context = applicationDbContext;
        }

        /// <summary>
        /// 迁移监控数据到lims系统数据库
        /// </summary>
        /// <returns></returns>
        [HttpGet("migration")]
        public ObjectResult Migration()
        {
            var res = monitorDevService.Migration();
            return new ObjectResult(Result.Success(res));
        }



        [HttpDelete("delete/batch")]
        public ObjectResult DeleteBatch([FromBody] List<int> ids)
        {
            if (ids == null || !ids.Any())
            {
                return new ObjectResult(Result.Error("请选择要删除的数据"));
            }

            _context.MonitorDevs.RemoveRange(_context.MonitorDevs.Where(m => ids.Contains(m.Id)));
            _context.SaveChanges();

            return new ObjectResult(Result.Success("删除成功"));
        }


        [HttpGet("selectByPage")]
        public ObjectResult Get(
            int pageNum = 1,
            int pageSize = 10,
            string? address = "",
            string? type = ""
        )
        {
            var res = monitorDevService.SelectByPage(pageNum, pageSize, address, type);
            return new ObjectResult(res);
        }

        [HttpPost("add")]
        public ObjectResult Add([FromBody] MonitorDevDto monitorDevDto)
        {
            monitorDevService.Add(monitorDevDto);
            return new ObjectResult(Result.Success("设备添加成功"));
        }

        [HttpPut("update")]
        public ObjectResult Update([FromBody] MonitorDevDto monitorDevDto)
        {
            monitorDevService.Update(monitorDevDto);
            return new ObjectResult(Result.Success("设备信息更新成功"));
        }

        [HttpDelete("delete/{id}")]
        public ObjectResult Delete(int id)
        {
            try
            {
                monitorDevService.Delete(id);
                return new ObjectResult(Result.Success("设备删除成功"));
            }
            catch (ServiceException ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
        }

        /// <summary>
        /// 批量导入接口
        /// </summary>
        /// <returns></returns>
        [HttpPost("import")]
        public ObjectResult import(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return new ObjectResult(Result.Error("文件不能为空！"));
            }

            var monitorDevs = new List<MonitorDev>();

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var stream = new MemoryStream())
            {
                file.CopyToAsync(stream);
                using (var package = new ExcelPackage(stream))
                {
                    var worksheet = package.Workbook.Worksheets[0]; // 读取第一个Sheet
                    int rowCount = worksheet.Dimension.Rows; // 获取行数

                    for (int row = 2; row <= rowCount; row++) // 跳过表头，从第2行开始
                    {
                        monitorDevs.Add(
                            new MonitorDev
                            {
                                Type = worksheet.Cells[row, 1].Text,
                                Address = worksheet.Cells[row, 2].Text,
                                Port = worksheet.Cells[row, 3].Text,
                                Account = worksheet.Cells[row, 4].Text,
                                Password = worksheet.Cells[row, 5].Text,
                                Area = worksheet.Cells[row, 6].Text,
                                //RtspUrl = worksheet.Cells[row, 7].Text 更新的时候自动生成
                                UrlId = worksheet.Cells[row, 8].Text,
                            }
                        );
                    }
                }
            }

            if (!monitorDevs.Any())
            {
                return new ObjectResult(Result.Error("Excel 文件为空或格式不正确！"));
            }

            var entityList = monitorDevs
                .Select(d => new MonitorDev
                {
                    Type = d.Type,
                    Address = d.Address,
                    Port = d.Port,
                    Account = d.Account,
                    Password = d.Password,
                    Area = d.Area,
                    RtspUrl = "",
                    UrlId = d.UrlId,
                })
                .ToList();

            _context.MonitorDevs.AddRange(entityList);
            _context.SaveChanges();

            return new ObjectResult(Result.Success("批量导入成功"));
        }

        [HttpGet("export")]
        public async Task<IActionResult> Export(
            string? address = "",
            string? type = "",
            string? ids = ""
        )
        {
            // 如果传入了 ids, 则根据 ids 进行筛选
            IQueryable<MonitorDev> monitorDevsQuery = _context.MonitorDevs;

            if (!string.IsNullOrEmpty(ids))
            {
                // 如果有 ids，按照 ids 筛选
                var idList = ids.Split(',').Select(id => Convert.ToInt32(id)).ToList();
                monitorDevsQuery = monitorDevsQuery.Where(dev => idList.Contains(dev.Id)); // 假设 MonitorDev 有 Id 字段
            }

            // 如果传入了 address 和 type，进行筛选
            if (!string.IsNullOrEmpty(address))
            {
                monitorDevsQuery = monitorDevsQuery.Where(dev => dev.Address == address);
            }

            if (!string.IsNullOrEmpty(type))
            {
                monitorDevsQuery = monitorDevsQuery.Where(dev => dev.Type == type);
            }

            var monitorDevs = await monitorDevsQuery.ToListAsync();

            // 设置 EPPlus 许可证
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("MonitorDevs"); // 添加一个新的工作表
                worksheet.Cells[1, 1].Value = "类型"; // 设置表头
                worksheet.Cells[1, 2].Value = "地址";
                worksheet.Cells[1, 3].Value = "端口";
                worksheet.Cells[1, 4].Value = "账号";
                worksheet.Cells[1, 5].Value = "密码";
                worksheet.Cells[1, 6].Value = "区域";
                worksheet.Cells[1, 7].Value = "RtspUrl";
                worksheet.Cells[1, 8].Value = "区域ID";

                if (monitorDevs.Any())
                {
                    // 填充数据
                    int row = 2;
                    foreach (var dev in monitorDevs)
                    {
                        worksheet.Cells[row, 1].Value = dev.Type;
                        worksheet.Cells[row, 2].Value = dev.Address;
                        worksheet.Cells[row, 3].Value = dev.Port;
                        worksheet.Cells[row, 4].Value = dev.Account;
                        worksheet.Cells[row, 5].Value = dev.Password;
                        worksheet.Cells[row, 6].Value = dev.Area;
                        worksheet.Cells[row, 7].Value = dev.RtspUrl;
                        worksheet.Cells[row, 8].Value = dev.UrlId;
                        row++;
                    }
                }

                // 设置响应内容类型和文件名
                var fileContent = package.GetAsByteArray();
                return File(
                    fileContent,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "MonitorDevs_Export.xlsx"
                );
            }
        }
    }
}
